<?php

/**
 * Created by PhpStorm.
 * User: jian
 * Date: 18-8-5
 * Time: 下午9:58
 */

namespace app\api\controller;

use think\Controller;
use think\Request;
use think\Session;
use think\Validate;

class Conmon extends Controller
{
    protected $request; //用来处理参数
    protected $validate; //用来验证数据/参数
    protected $params; //过滤后符合要求的参数

    /********** 不验证token *********/
    protected $path = array(
        'api/users/login',
        'api/users/login/',
        '/api/users/login/'
    );

    protected function _initialize ()
    {
        parent::_initialize();
        $this->request = Request::instance();
        $this->check_time($this->request->header('time'));
        $this->check_token($this->request);
    }

    /*
     * 验证请求是否超时
     * @param [array] $arr [包含时间戳的参数数组]
     * @return [json]  [检测结果]
     */
    public function check_time ($arr)
    {
        if (is_null($arr)) {
            $this->return_msg(400, '缺少time');
        }
        if (time() - intval($arr) > 10000000) {
            $this->return_msg(400, '请求超时');
        }
    }

    /**
     * 验证Token
     * @param $info
     */
    public function check_token ($info)
    {
        $this->request = Request::instance();
        if (!in_array($this->request->path(), $this->path)) {
            /********** api传过来的token *********/
            $app_token = $this->request->header('Authorization');
            if (!isset($app_token) || empty($app_token)) {
                $this->return_msg(400, 'token不能为空' . $this->request->path());
            }
            /********** 对比token，返回结果 *********/
            if ($app_token !== Session::get('token')) {
                $this->return_msg(400, 'token不正确');
            }
        } else {
            /********** 服务器端生成token *********/
            $service_token = '';
            foreach ($this->request->param() as $key => $value) {
                $service_token .= md5($value);
            }
            $service_token = md5('sy_' . $service_token); //服务端及时生成的token
            Session::set('token', $service_token);
        }

    }

    /**
     * @param        $code 状态码
     * @param string $msg 内容
     * @param array $data
     *
     * @return json
     */
    public function return_msg ($code, $msg = '', $data = [])
    {
        $return_date['code'] = $code;
        $return_date['msg']  = $msg;
        $return_date['data'] = $data;
        echo json_encode($return_date);
        die();
    }
}
